﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Domain.Entities
{
    public class MacAddress
    {
        const int macLength = 12;
        string _mac;
        private MacAddress(string mac)
        {
            _mac = mac;
        }
        public string Value
        {
            get { return _mac; }
        }
        public static MacAddress Create(string arg)
        {
            MacAddress mac;
            if (TryParse(arg, out mac))
            {
                return mac;
            }
            else
            {
                return null;
            }
        }
        static public bool TryParse(string value, out MacAddress result)
        {
            value = value.Trim();
            value = value.Replace("-", "");
            value = value.Replace(".", "");
            value = value.Replace(":", "");
            value = value.ToUpper();

            char[] oldValue = value.ToCharArray();
            StringBuilder stdFormatMac = new StringBuilder();
            string pattern = @"\d|[A-F]";
            for (int i = 0; i < oldValue.Length; i++)
            {
                Match m = Regex.Match(oldValue[i].ToString(), pattern);
                if (m.Success)
                {
                    stdFormatMac.Append(oldValue[i]);
                }
                else
                {
                    result = null;
                    return false;
                }
            }
            if (oldValue.Length != macLength)
            {
                result = null;
                return false;
            }
            result = new MacAddress(stdFormatMac.ToString());
            return true;
        }
    }
}